﻿namespace TradePublish.SysThread.Sys
{
    using log4net;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;
    using System.Threading;
    using TradePublish.Service.impl;
    using TradePublish.Entity;
    using TradePublish.Dao;
    using TradePublish.SysThread.Grasp;
    using System.Collections;
    using System.Net.Sockets;
    using System.Net;
    using TradePublish.Common;
    using System.Text;

    internal class SearchEmailTaskClientThread
    {
        private Thread doThread;
        private ILog log = null;
        Socket clientSocket;
        String issue = null;

        public SearchEmailTaskClientThread()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        public void start()
        {
            this.doThread = new Thread(new ThreadStart(this.threadWork));
            this.doThread.IsBackground = true;
            this.doThread.Start();
        }

        private Hashtable getSocketData()
        {
            //将网络端点表示为IP地址和端口 用于socket侦听时绑定    

            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Global.serverIpInlan), 3001); //填写自己电脑的IP或者其他电脑的IP，如果是其他电脑IP的话需将ConsoleApplication_socketServer工程放在对应的电脑上。  
            clientSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 30000);
            clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 360000);
            //将Socket连接到服务器    
            try
            { 
                clientSocket.Connect(ipep);  
                Byte[] outBuffer = new Byte[1024]; 
                Byte[] inBuffer = new Byte[10240]; 
                //发送消息   
                outBuffer = Encoding.UTF8.GetBytes(Global.clientNo+ ":READY");
                clientSocket.Send(outBuffer, outBuffer.Length, SocketFlags.None);
                //接收服务器端信息                
                clientSocket.Receive(inBuffer, 10240, SocketFlags.None);//如果接收的消息为空 阻塞 当前循环  
                String receiveData =  Encoding.UTF8.GetString(inBuffer);
                log.Info("服务器说：" + receiveData);
                Hashtable rtn = new Hashtable();
                issue = receiveData.Substring(0, receiveData.IndexOf(":"));
                String[] d = receiveData.Substring(receiveData.IndexOf(":")+1).Split('\t');
                for (int i = 0; i < d.Length-1;i++ )
                {
                    log.Info("【【【【【】】】】】" + d[i]);
                    if (d[i] != null && !d[i].Trim().Replace("\r","").Replace("\n","").Equals(""))
                    {
                        rtn.Add(d[i],"1");//value无用
                    } 
                }
                return rtn;
            }

            catch(Exception ex)
            {
                throw ex;

            }
        }
        public void threadWork()
        { 
            
            ApplyUserContractManager manager = new ApplyUserContractManager();
            DissentTradeDao dao = new DissentTradeDao();
            while (true)
            {
                Hashtable applyUserNames = null;
                try
                {
                    issue = null;
                   applyUserNames = getSocketData();
                    
                }
                catch (Exception ex)
                {
                    log.Error("Socket远程获得任务发生异常："+ex.Message);
                    Thread.Sleep(5000);
                    continue;
                }
                if (applyUserNames == null || applyUserNames.Count == 0 || issue == null || issue.Equals("0"))
                {
                    log.Info("NNNNNNNNNNNNNNNNN===从Socket中未发现需要采集的申请人！");
                    Thread.Sleep(60000);
                }
                else
                {
                    //最多10个申请人。
                    foreach (DictionaryEntry objDE in applyUserNames)
                { 
                    
                        int num2 = 0;
                        while (true)
                        {
                            try
                            {
                                //if (!manager.hasGrasped(applyUserNames[i].ToString()))
                                //{ 
                                //不管是否采集过，均采集一遍
                                    log.Debug("开始从搜索引擎采集邮箱");
                                    List<ApplyUserContract> contracts = new SearchEmailManager().grasp(objDE.Key.ToString()); 

                                    log.Debug("开始采集阿里巴巴-旺旺号码");
                                    List<ApplyUserContract> contracts1 = new AlibabaManager().graspContract(objDE.Key.ToString());
                                    if (contracts1 != null)
                                    {
                                        if (contracts == null)
                                        {
                                            contracts = new List<ApplyUserContract>();
                                        }
                                        for (int c = 0; c < contracts1.Count; c++)
                                        {
                                            contracts.Add(contracts1[c]);
                                        }
                                    }
                                    manager.saveContract(contracts);
                                    dao.setHasSearchEmail(objDE.Key.ToString(),issue);
                                //}
                                //else
                                //{
                                //    log.Info(applyUserNames[i].ToString() + " 已采集过，本次无需再次采集.");
                                //}
                                break;
                            }
                            catch (Exception exception)
                            {
                                num2++;
                                this.log.Error(string.Concat(new object[] { "%%%%%%采集", objDE.Key.ToString(), "联系方式第", num2, "次发送异常：" }), exception);
                                if (num2 <= 3)
                                {
                                    Thread.Sleep(60000);
                                }
                                else
                                {
                                    break;//超过3次就跳过
                                }
                            }
                        }
                    }
                }
            }
            log.Error("KKKKKKKKKKKKKKKKKKKKKKKKKK===SearchEmailTaskClientThread线程死掉了");
            
        }
    }
}

